using System;
using System.Diagnostics;
using System.Reflection;
using System.IO;

namespace CUtil
{
	/// <summary>
	/// Summary description for ReflectionClass.
	/// </summary>
	public class ReflectionClass
	{
		public ReflectionClass()
		{
			
		}
		/// <summary>
		/// GetAllControlNames helper method for InspectDesignAssemblies
		/// </summary>
		public static Type[] GetAvailableTypes(Assembly ass)
		{
			 Type[]  MyTypes = null;
			System.Diagnostics.Debug.Assert(ass != null, "Data: ReflectionClass, Inidcator assembly = null");
			try
			{
				System.Collections.ArrayList MyTypeNames = new System.Collections.ArrayList();
				
				try
				{
					MyTypes = ass.GetTypes();// GetExportedTypes
				}
				catch(Exception e)
				{
					System.Diagnostics.Debug.Assert(false, "Could not get types from assembly - perhaps a local copy " +
						"of this dll with another version is there ? " + e.Message);
				}
					

	
				return MyTypes;
			}
			catch(Exception e)
			{
				System.Diagnostics.Debug.Assert(false, "Data ::Error getting all available UserControls : " + e.ToString());
				return null;
			}		

		}
		/// <summary>
		/// sub - method of the GetUserControlAssembly - finds an assembly by name
		/// </summary>
		public static Assembly FindAssembly(string d,string MyFilename) 
		{
			//check whether the directory exists
			if (false == System.IO.Directory.Exists(d)) 
			{
				return null;
			}
			// todo check whether the directory exists
		
			DirectoryInfo dir = new DirectoryInfo(d);
			
			foreach (FileInfo file in dir.GetFiles("*.dll")) 
			{
				if(file.Name==	MyFilename)
				{
					try 
					{
						Assembly assembly = Assembly.LoadFrom(file.FullName);			
						return assembly;
					}
					catch (Exception e) 
					{
						System.Diagnostics.Debug.WriteLine(e.ToString());
						return null;
						//throw(e);
					}
				}
			}
			return null;

		}
		private void aa()
		{
			
		}
		public static object CreateInstanceOfClassFromAssembly(Assembly ass, string MyDataClassN)
		{
			Debug.Assert(ass != null, "Assembly is null while trying to operate on it ");
			Type[] MyTypes = GetAvailableTypes(ass);
			Type MyType = null;

						
			
			foreach(Type Mytyp in MyTypes)
			{
				if(Mytyp.Name == MyDataClassN.ToString())
				{
					MyType=Mytyp;
					//MyCategory=MyType.Name ;
					break;
				}
			}
			object o =(Activator.CreateInstance(MyType));

			return o;



		}
	}
}
